package com.avic.rong.fragment.collect;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.avic.rong.R;
import com.avic.rong.activity.mine.CollectionActivity;
import com.avic.rong.adapter.collect.QuestAnswerAdapter;
import com.avic.rong.api.CollectThumbNumApi;
import com.avic.rong.api.collect.DeleteCollectApi;
import com.avic.rong.api.collect.QuestAnswerApi;
import com.avic.rong.bean.collect.QuestAnswerBean;
import com.avic.rong.fragment.BaseLazyFragment;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class QuestAnswerFragment extends BaseLazyFragment implements OnRefreshLoadMoreListener{


    @BindView(R.id.recv_quest_answer)
    RecyclerView recv_quest_answer;
    @BindView(R.id.srl_quest_answer)
    SmartRefreshLayout srl_quest_answer;
    @BindView(R.id.tv_wushujv)
    TextView tvWuShujv;

    private View view;
    private Unbinder unbinder;
    private QuestAnswerAdapter questAnswerAdapter;
    private String logintoken;
    private int pageNo = 1;
    private boolean isRefresh;
    private QuestAnswerApi questAnswerApi;
    private LoadingLayout loading_layout;

    public QuestAnswerFragment() {
        // Required empty public constructor
    }

  //  private String token = "w4/b+EQcZZnFlmpDOn6EJH49BIWDoQfvAqU8Ief4OOsLF2xTVRyFnfxTic0l1spUK1MBOtGvWOplYHrSER4cmsIN4jlZeYpVKSEnTQhapbu4/s+HGJ9KlA==";
    private ArrayList<QuestAnswerBean> mList;
    private String title;
    private Context mContext;

    public static QuestAnswerFragment getInstance(String title, Context mContext) {
        QuestAnswerFragment questAnswerFragment = new QuestAnswerFragment();
        questAnswerFragment.title = title;
        questAnswerFragment.mContext = mContext;
        return questAnswerFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (SharedPreferencesUtil.isLogin()) {
            logintoken = SharedPreferencesUtil.getLoginToken();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_quest_answer, container, false);
        unbinder = ButterKnife.bind(this, inflate);

        loading_layout = inflate.findViewById(R.id.loading_layout);
        loading_layout.setStatus(LoadingLayout.LOADING);


        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(questAnswerApi);
                loading_layout.setStatus(LoadingLayout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recv_quest_answer.setLayoutManager(linearLayoutManager);

        mList = new ArrayList<>();
        questAnswerAdapter = new QuestAnswerAdapter(mContext, mList,logintoken);
        recv_quest_answer.setAdapter(questAnswerAdapter);


        //删除回答回调
        questAnswerAdapter.setQuestAnswerButtonClick(new QuestAnswerAdapter.QuestAnswerButtonClick() {
            @Override
            public void onClick(QuestAnswerBean bean, int position,int type,boolean isRefresh) {
                DeleteCollectApi deleteCollectApi = new DeleteCollectApi((CollectionActivity) getActivity(),new MyDeleteQuestAnswerListener(bean,isRefresh) );
                deleteCollectApi.setArgument(logintoken,type,bean.getId());
                HttpManager.getInstance().doHttpDeal(deleteCollectApi);
            }
        });



        srl_quest_answer.setOnRefreshLoadMoreListener(this);

        return inflate;
    }

    @Override
    public void loadData() {
        initData();
    }

    //删除回调
    public class MyDeleteQuestAnswerListener extends HttpOnNextListener<BaseResultEntity>{

        QuestAnswerBean bean;
        boolean isRefresh;

        public MyDeleteQuestAnswerListener(QuestAnswerBean bean, boolean isRefresh) {
            this.bean = bean;
            this.isRefresh = isRefresh;
        }

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){

                if (isRefresh){
                    mList.remove(bean);
                }else {
                    CollectThumbNumApi collectThumbNumApi = new CollectThumbNumApi((CollectionActivity) mContext, new MyCollectNumListener());
                    collectThumbNumApi.setArgument("/answer/collectNum", bean.getId());
                    HttpManager.getInstance().doHttpDeal(collectThumbNumApi);
                }
                ToastTools.showPublicToast(baseResultEntity.getMsg());
            }
        }
    }


    public class MyCollectNumListener extends HttpOnNextListener<BaseResultEntity>{

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)){
                ToastTools.showToast(baseResultEntity.getMsg());
                return;
            }
        }
    }


    private void initData() {
        questAnswerApi = new QuestAnswerApi((CollectionActivity) getActivity(), questAnswerListener);
        questAnswerApi.setArgument(logintoken, pageNo);
        questAnswerApi.setCache(false);
//        questAnswerApi.setCancel(false);
//        questAnswerApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(questAnswerApi);
    }

    HttpOnNextListener<BaseResultEntity> questAnswerListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                Log.e("QuestAnswerApi", "onNext: " + baseResultEntity.getResult());
                List<QuestAnswerBean> data = (List<QuestAnswerBean>) baseResultEntity.getData();
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (isRefresh) {
                    mList.clear();
                }
                if (data!=null&&data.size()>0) {
                    questAnswerAdapter.setData(data);
                }

                if (mList!=null&&mList.size()<=0){
                    loading_layout.setStatus(LoadingLayout.EMPTY);
                    loading_layout.setEmptyImageVisible(true);
                    loading_layout.setEmptyText("您还未添加过收藏哦~");
                    loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                }

                if (srl_quest_answer!=null) {
                    if (isRefresh) {
                        srl_quest_answer.finishRefresh();
                    } else {
                        srl_quest_answer.finishLoadMore();
                    }
                }
            }else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        pageNo = pageNo + 1;
        questAnswerApi.setPageNo(pageNo);
        HttpManager.getInstance().doHttpDeal(questAnswerApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        pageNo = 1;
        questAnswerApi.setPageNo(pageNo);
        HttpManager.getInstance().doHttpDeal(questAnswerApi);
    }
}
